import { defineStore } from 'pinia';

import { getAllApi } from '@/api/system/dict';
import type { DictItem } from '@/api/system/dict/types';

export interface DictState {
  dictMap: Map<string, DictItem[]>;
}

const useDictStore = defineStore('client-dict', {
  persist: {
    storage: localStorage,
    afterRestore: (context) => {
      // 在从存储恢复后，将普通对象转换回Map
      const dictObj = context.store.$state.dictMap;
      if (dictObj && !(dictObj instanceof Map)) {
        context.store.$state.dictMap = new Map<string, DictItem[]>(
          Object.entries(dictObj)
        );
      }
    },
  },
  state: (): DictState => ({
    dictMap: new Map<string, DictItem[]>(),
  }),
  getters: {
    getDictMap(): Map<string, DictItem[]> {
      return this.dictMap;
    },
  },
  actions: {
    async initDict(): Promise<void> {
      const data = await getAllApi();
      if (data) {
        this.dictMap = data;
      } else {
        this.dictMap = new Map<string, DictItem[]>();
      }
    },
    getLabel(name: string, value: number): string {
      const item: DictItem | undefined = this.getItem(name, value);
      if (item) {
        return item.label;
      }
      return '';
    },
    getLabelByExtend(name: string, value: string, key = 'code'): string {
      const items: DictItem[] | undefined = this.getItems(name);
      if (items && items.length > 0 && value) {
        const foundItem = items.find((item) => value === item.extend[key]);
        return foundItem?.label || '';
      }
      return '';
    },
    getExtend(name: string, value: number): Record<string, any> {
      const item: DictItem | undefined = this.getItem(name, value);
      if (item) {
        return item.extend;
      }
      return {};
    },
    getItem(name: string, value: number): DictItem | undefined {
      const items: DictItem[] | undefined = this.getItems(name);
      if (items && items.length > 0 && value) {
        return items.find((item) => value === item.value);
      }
      return undefined;
    },
    getItems(name: string): DictItem[] | undefined {
      if (this.dictMap && name) {
        if (this.dictMap instanceof Map) {
          return this.dictMap.get(name);
        } else {
          const map = new Map<string, DictItem[]>(Object.entries(this.dictMap));
          return map.get(name);
        }
      }
      return undefined;
    },
  },
});

export default useDictStore;
